import Snake from "./Snake";
import {Direction} from './types';


export class Game {
  canvas?: HTMLCanvasElement;
  ctx: CanvasRenderingContext2D | null = null;

  //启动游戏的定时器id
  timeid: NodeJS.Timeout | null = null;

  snake: Snake | null = null;

  constructor(
    public width: number,
    public height: number,
    public size: number = 10,
    public blockSize: number = 20
  ) {
    ////创建 内置canvas
    this.canvas = document.createElement("canvas");
    this.ctx = this.canvas.getContext("2d");
  }

  //TODO 初始化游戏
  init() {
    if (this.canvas) {
      //   console.log("初始化游戏");
      this.width = this.canvas.width = Math.max(window.innerWidth, this.width) - 10;
      this.height = this.canvas.height = Math.max(window.innerHeight, this.height) - 10;
      
      //设置游戏背景
      this.canvas.style.backgroundColor = "rgb(200,100,100)";

      //添加游戏画布到body
      document.body.appendChild(this.canvas);

      // 初始化蛇
      this.snake = new Snake(this.size, this.blockSize, this.ctx);

      //绘制蛇
      this.snake.draw();
    }
  }

  start(speed: number = 300) {
    console.log("游戏开始");
    // this.go();

    this.timeid = setInterval(() => {
        this.go();
    }, speed);
  }

  public go() {
    if (this.snake && this.ctx) {
      //清空画布
      this.ctx.clearRect(0, 0, this.width, this.height);
      //移动蛇
      this.snake?.move();
      //绘制蛇
      this.snake?.draw();
    }
  }

  pause() {
    console.log("游戏暂停");

    clearInterval(this.timeid!);
  }

  changeDirection(direction: Direction) {
    this.snake?.changeDirection(direction);
  }
}
